package com.feilx.changggou.seckill.service.impl;

import com.alibaba.fastjson.JSON;
import com.changgou.bean.PageVo;
import com.changgou.bean.Query;
import com.changgou.bean.QueryCondition;
import com.changgou.utils.DateUtil;
import com.changgou.utils.DateUtils;
import com.changgou.utils.RedisUtils;
import com.feilx.changggou.seckill.common.LoadSeckillToRedis;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.feilx.changggou.seckill.dao.TbSeckillDao;
import com.feilx.changggou.seckill.entity.TbSeckillEntity;
import com.feilx.changggou.seckill.service.TbSeckillService;

import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;


@Service
public class TbSeckillServiceImpl extends ServiceImpl<TbSeckillDao, TbSeckillEntity> implements TbSeckillService {

    @Autowired
    private RedisUtils redisUtils;

    @Override
    public PageVo queryPage(QueryCondition params) {
        IPage<TbSeckillEntity> page = this.page(
                new Query<TbSeckillEntity>().getPage(params),
                new QueryWrapper<TbSeckillEntity>()
        );

        return new PageVo(page);
    }

    @Override
    public List<TbSeckillEntity> querySeckill(Date date, Set<String> ex) {
        QueryWrapper<TbSeckillEntity> queryWrapper = new QueryWrapper();
        // 秒杀商品 状态为通过
        queryWrapper.eq("status","1");
        // 库存>0
        queryWrapper.gt("stock_count",0);
        // 开始时间大于等于当前时间
        queryWrapper.ge("start_time",date);
        // 结束时间小于等于当前时间加2
        queryWrapper.lt("end_time", DateUtil.addDateHour(date,2));
        // 排除已有的秒杀商品
        queryWrapper.notIn("id",ex);
        List<TbSeckillEntity> list = this.list(queryWrapper);
        return list;
    }

    @Override
    public List<TbSeckillEntity> querySecillGoods(String time) {
        List<Object> hvalues = redisUtils.hvalues(LoadSeckillToRedis.REDIS_KILL_KEY + time);
        List<TbSeckillEntity> list = new ArrayList<>();
        hvalues.forEach(data ->{
            TbSeckillEntity aas = (TbSeckillEntity)data;
            list.add(aas);
        });
        return list;
    }

    @Override
    public TbSeckillEntity getSecillGood(String time,String id) {
        TbSeckillEntity entity = (TbSeckillEntity)redisUtils.hget(LoadSeckillToRedis.REDIS_KILL_KEY + time, id);
        return entity;
    }

}
